package cn.kgc.util;


import cn.kgc.annotation.Value;
import cn.kgc.entity.Student;


import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/2/15
 * @Description:
 */
public class Utils {

    private static Map<String,Object> container = new HashMap<>();
    static {
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("bean.properties");
        //InputStream resourceAsStream = Utils.class.getClassLoader().getResourceAsStream("bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            Enumeration<Object> keys = properties.keys();
            while (keys.hasMoreElements()){
                String key = (String) keys.nextElement();
                String value = (String) properties.get(key);
                Class<?> clazz = Class.forName(value);
                System.out.println("clazz = " + clazz);
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
                declaredConstructor.setAccessible(true);
                Object obj = declaredConstructor.newInstance();
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    Value annotation = declaredField.getAnnotation(Value.class);
                    if (annotation !=null) {
                        String value1 =  annotation.value();
                        declaredField.set(obj,value1);
                    }
                }


                container.put(key,obj);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static Object getBean(String beanName){
        return container.get(beanName);
    }
    public static <T> T getBean(String beanName,Class<T> clazz){
        Object o = container.get(beanName);
        return clazz.cast(o);
    }
    public static void main(String[] args) {
        //Person person = (Person) NewBeanFactory.getBean("Person");
        Student person1 = Utils.getBean("student", Student.class);
        System.out.println("person1 = " + person1);

    }

}
